import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

# 导入数据
data = pd.read_excel('第二章 图表(前15).xlsx',sheet_name='3 渐变圆角柱形图',usecols='B:C',skiprows=1)

# 设置渐变函数
def gradient_bar(x, y, ax, colormap='Blues'):   # 选用蓝色色卡
    n_bars = len(x)
    bar_colors = plt.get_cmap(colormap)(np.linspace(0.5, 0.9, 100))  # 设置渐变起始点与终止点

    # 创建柱子
    for i in range(n_bars):
        left = i
        bottom = 0
        width = 0.6
        height = y[i]

        # 创建渐变效果
        polys = []
        for j in range(100):
            h = height * (j / 100)
            verts_j = [
                (left, bottom + h),
                (left, bottom + height),
                (left + width, bottom + height),
                (left + width, bottom + h),
                (left, bottom + h)
            ]
            polys.append(verts_j)

        poly = PolyCollection(polys, facecolors=bar_colors)
        ax.add_collection(poly)

    ax.autoscale_view()

# 创建图形和坐标轴
fig, ax = plt.subplots(figsize=(8, 6))

# 设置背景颜色
fig.patch.set_facecolor('#00002d')
ax.set_facecolor('#00002d')

# 设置X轴和Y轴数据
x = np.arange(len(data['商品']))  # X轴位置
y = data['销量']  # Y轴高度

# 绘制渐变柱形图
gradient_bar(x, y, ax)

# 设置X轴标签
ax.set_xticks(x+0.3)
ax.set_xticklabels(data['商品'], color='w')

# 设置Y轴标签颜色为白色
ax.set_yticklabels(ax.get_yticks(), color='w')

# 添加网格线
ax.grid(True, axis='y' ,linestyle='--', linewidth=0.5, color='w')

# 隐藏边框
for spine in ax.spines.values():
    spine.set_visible(False)

# 输出每个柱子的值
for i in range(len(x)):
    ax.text(x[i] + 0.3, y[i] + 0.1, f'{int(y[i])}', ha='center', va='bottom', color='w', fontsize=10)

# 调整图形位置
plt.subplots_adjust(top=0.8)  # 留出空间给标题

# 添加标题
plt.text(0, 1.15, '3月商品销量对比', color='w', fontsize=24, transform=ax.transAxes)
plt.text(0, 1.05, '防晒销量最多，3月销量856；面膜最少，3月销量523', color='w', fontsize=16, transform=ax.transAxes)

# 导出图片
#plt.savefig('D:/python charm/01/可视化/第二章前15/图片/渐变圆角柱形图.png', dpi=300, bbox_inches='tight', facecolor='#00002d')

# 显示图形
plt.show()